package com.baizhi.controller;

import com.baizhi.entity.Role;
import com.baizhi.service.RoleService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("role")
@RequiresRoles("admin")

public class RoleController {

    @Autowired
    private RoleService roleService;

    @ExceptionHandler(RuntimeException.class)
    @RequestMapping("getAll")
    @ResponseBody
    public Map getAllRoles() {
        HashMap map = new HashMap<>();
        try {
            List<Role> all = roleService.findAll();
            map.put("code", 0);
            map.put("data", all);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        return map;
    }

    @ExceptionHandler(RuntimeException.class)
    @RequestMapping("delByName")
    @ResponseBody
    public Boolean deleteRoleByName(Role role) {

        try {
            roleService.removeRoleByName(role.getRoleName());
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        return true;
    }

    @ExceptionHandler(RuntimeException.class)
    @RequestMapping("getOne")
    @ResponseBody
    public Role getOne(Role role) {
        try {
            return role = roleService.findRoleByName(role.getRoleName());
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }


    @ExceptionHandler(RuntimeException.class)
    @RequestMapping("addOne")
    @ResponseBody
    public Boolean addRole(Role role) {

        try {
            roleService.addRole(role);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        return true;
    }

    @ExceptionHandler(RuntimeException.class)
    @RequestMapping("update")
    @ResponseBody
    public Boolean updateRole(Role role) {

        try {
            roleService.renovateRole(role);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        return true;
    }
}
